#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //设置窗口标题
    this->setWindowTitle("客户端 ");
    //实例化tcp对象
    socket = new QTcpSocket(this);

    //向服务器发起连接
    socket->connectToHost("127.0.0.1", 8082);
    //确认是否连接成功
    if(!socket->waitForConnected())
    {
        QMessageBox::critical(this, "连接服务器出错", socket->errorString());
        return;
    }

    //绑定接收到消息的信号槽函数
    connect(socket, &QTcpSocket::readyRead, this, [=](){
        //获取接收到的内容
        QString message = socket->readAll();
        //将内容打印到对话框中
        QString log = "服务器: " + message;
        ui->listWidget->addItem(log);
    });
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    //获取输入框的内容
    QString message = ui->lineEdit->text();
    //将内容发送给服务器
    socket->write(message.toUtf8());
    //将内容打印到对话框中
    ui->listWidget->addItem("客户端: " + message);
    //情况输入框
    ui->lineEdit->clear();
}

